'''
Created on Oct 11, 2009

@author: jaimeblasco
'''
from fastflux import *
from fastflux.monitor.models import *
import DNS
import time
import re
import urllib
#import pwhois
from time import strftime
import time
import logging
import GeoIP

gi = GeoIP.open('GeoLiteCity.dat', GeoIP.GEOIP_STANDARD)

logger = logging.getLogger("fastflux")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)

server = "80.58.0.33"
mark = 8

def makeRequest(domain):
    ips = []
    try:
        req = DNS.Request( name=domain, qtype="A", protocol= "udp", server=server )
        r = req.req()
        print r.answers
        for d in r.answers:
            ips.append(d['data'])
            #logger.debug("Adding %s" % d['data'])
        return ips
    except:
        logger.debug("Error retrieving nodes for %s" % domain)
        return ips

def getGeoData(ip):
    gir = gi.record_by_addr(ip)
    return gir
    
def main():
    logger.info("Fastflux Monitor Active")
    domains = Domain.objects.filter(active=1)
    for d in domains:
        logger.debug("Processing %s" % d.name)
        ips = makeRequest(d.name)
        count = len(ips)
        logger.debug("Returned %d records for %s" % (count, d.name))
        if count > mark:
            d.count = 0
            d.save()
            logger.info("%s mark as fastflux domain" % d.name)
            for i in ips:
                try:
                    node1 = Node.objects.get(ip=i)
                    match = False
                    for dom in node1.domain.all():
                        #print dom.name
                        if dom.name == d.name:
                            match = True
                    if not match:
                        node1.domain.add(d)
                        node1.save()
                        logger.info("Adding new domain to %s" % i)
                except:
                    gir = getGeoData(i)
                    logger.info("Adding %s" % i)
                    if gir:
                        city = gir['city']
                        if city:
                            city = city.replace('\\', '')
                        node = Node(ip=i, latitude=gir['latitude'], longitude=gir['longitude'], countryName=gir['country_name'], countryCode=gir['country_code'], city=city)
                        node.save()
                    else:
                        node = Node(ip=i)
                        node.save()
                    
                    node.domain.add(d)
        else:
            d.count = d.count + 1
        if d.count == 10:
            d.active = 0
        d.save()

if __name__ == '__main__':
    while 1:
        main()
        time.sleep(30)




